package com.zzyl.nursing.service.impl;

import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jackson.JsonComponentModule;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import javax.script.ScriptEngine;
import javax.script.ScriptException;

import static com.zzyl.common.constant.CacheConstants.IOT_DEVICE_LAST_DATA;

/**
 * 报警规则Service业务层处理
 *
 * @author zmc
 * @date 2025-10-20
 */
@Slf4j
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper,AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private JsonComponentModule jsonComponentModule;
    @Autowired
    private LocaleChangeInterceptor localeChangeInterceptor;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return save(alertRule)?1:0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return updateById(alertRule)?1:0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return removeById(id)?1:0;
    }
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void alertFilter() {
        List<AlertRule> list = this.list();
        if (CollUtil.isEmpty(list)) {
            return;
        }
        //查询设备上报的数据
        List<Object> values = redisTemplate.boundHashOps(IOT_DEVICE_LAST_DATA).values();
        if (CollUtil.isEmpty(values)) {
            return;
        }

        List<DeviceData> deviceDataList = new ArrayList<>();
        //把数据放到一个大集合中
        for (Object value : values) {
            List<DeviceData> deviceDataList1 = JSONUtil.toList(value.toString(), DeviceData.class);
            deviceDataList.addAll(deviceDataList1);

        }
        for (DeviceData deviceData : deviceDataList) {
            System.out.println("------------------------"+deviceData);
            alterFiler(deviceData);
        }

    }
    int alertFilterCount =0;
    private void alterFiler(DeviceData deviceData) {
        log.info("进入alterFiler方法次数:"+ alertFilterCount);
        alertFilterCount ++;
        //对所有设备查询心率
        LambdaQueryWrapper<AlertRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AlertRule::getProductKey,deviceData.getProductKey());
        queryWrapper.eq(AlertRule::getFunctionId,deviceData.getFunctionId());
        queryWrapper.eq(AlertRule::getIotId,-1);
        List<AlertRule> ruleList = this.list(queryWrapper);
        //指定设备查询心率
        LambdaQueryWrapper<AlertRule> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AlertRule::getProductKey,deviceData.getProductKey());
        queryWrapper1.eq(AlertRule::getFunctionId,deviceData.getFunctionId());
        queryWrapper1.eq(AlertRule::getIotId,deviceData.getIotId());
        List<AlertRule> ruleList1 = this.list(queryWrapper1);
        //合并两个集合
        CollUtil.addAll(ruleList,ruleList1);
        if(CollUtil.isEmpty(ruleList)){
            return;
        }

        for (AlertRule alertRule : ruleList) {
            deviceDataAlarmHandler(alertRule,deviceData);
        }
    }
    @Autowired
    private ScriptEngine scriptEngine;

    private void deviceDataAlarmHandler(AlertRule alertRule, DeviceData deviceData) {
        log.info("开始第一层效验");
        String period = alertRule.getAlertEffectivePeriod();
        String[] periods = period.split("~");
        LocalTime startTime = LocalTime.parse(periods[0]);
        LocalTime endTime = LocalTime.parse(periods[1]);
        LocalTime alarmTIme = deviceData.getAlarmTime().toLocalTime();
        if (alarmTIme.isBefore(startTime)||alarmTIme.isAfter(endTime)) {
            return;
        }
        String alertCountKey=  CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+deviceData.getIotId()+ deviceData.getProductKey()+alertRule.getFunctionId()+alertRule.getId();
        String slientKey = CacheConstants.ALERT_SILENT_PREFIX+deviceData.getIotId()+ deviceData.getProductKey()+ alertRule.getFunctionId()+alertRule.getId();
        log.info("开始第二层效验");
        String expresstion  =     deviceData.getDataValue() + alertRule.getOperator() + alertRule.getValue();

        Boolean isReach = false;

        try {
            isReach = (Boolean)scriptEngine.eval(expresstion);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        if (isReach) {
            redisTemplate.delete(alertCountKey);
            return;
        }
        log.info("开始第三层效验");
        String string = redisTemplate.boundValueOps(slientKey).get();

        if (string!=null) {
            return;
        }
        log.info("开始第四层效验");

        Long alertCount = redisTemplate.boundValueOps(alertCountKey).increment();

        if(alertCount>=alertRule.getDuration()){
            log.info("可以报警了---------------------------");
        }
        redisTemplate.boundValueOps(slientKey).set("",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        // 插入报警数据
        insertAlertData(alertRule, deviceData);
    }

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IAlertDataService alertDataService;

    // alert:
// deviceMaintainerRole
    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.managerRole}")
    private String managerRole;


    private void insertAlertData(AlertRule alertRule, DeviceData deviceData) {
        //判断是什么数据
        List<Long> list = new ArrayList<>();
        if (deviceData.getLocationType().equals(0)){
            list = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
        }else {
            if (deviceData.getPhysicalLocationType().equals(1)){
                list = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
            }else if (deviceData.getPhysicalLocationType().equals(2)){
                list = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
            List<Long> list1 = sysUserRoleMapper.selectUserIdByRoleName(managerRole);
            Collection<Long> longs = CollUtil.addAll(list, list1);
            list = CollUtil.distinct(longs);
            List<AlertData> alertDataList = new ArrayList<>();
            for (long userId : list){
                AlertData alertData = new AlertData();
                alertData.setId(deviceData.getId());
                alertData.setIotId(deviceData.getIotId());
                alertData.setDeviceName(deviceData.getDeviceName());
                alertData.setProductKey(deviceData.getProductKey());
                alertData.setProductName(deviceData.getProductName());
                alertData.setFunctionId(deviceData.getFunctionId());
                alertData.setAccessLocation(deviceData.getAccessLocation());
                alertData.setLocationType(deviceData.getLocationType());
                alertData.setPhysicalLocationType(deviceData.getPhysicalLocationType());
                alertData.setDeviceDescription(deviceData.getDeviceDescription());
                alertData.setDataValue(deviceData.getDataValue());
                alertData.setAlertRuleId(deviceData.getId());
                //报警原因 设定格式为   功能名+运算符+阈值+持续周期+沉默周期
                alertData.setAlertReason(deviceData.getFunctionId()+alertRule.getOperator()+alertRule.getDuration()+alertRule.getAlertSilentPeriod());

                alertData.setType(deviceData.getLocationType());
                alertData.setStatus(0);
                alertData.setUserId(userId);
                alertDataList.add(alertData);
            }
            alertDataService.saveBatch(alertDataList);
        }
    }

}